package com.demo.index;

import com.demo.annotation.EmptyParaValidate;
import com.demo.utils.PhotoQrCode;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 本 demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法
 * 详见 JFinal 俱乐部: http://jfinal.com/club
 * 
 * IndexController
 */
public class IndexController extends Controller {
	public void index() {
		render("index.html");
	}

	private static ConcurrentHashMap<String, Object> tadeState = new ConcurrentHashMap();

	static {}
	/**
	 * 长连接获取状态
	 */
	private static Long timeOut= 15000L;
	private static String tradeNo = "no";
	@EmptyParaValidate("tradeNo")
	public void longConnect() throws InterruptedException {
		Ret ret = null;
		String text= "";
		Boolean isTimeOut = false;
		String no = getPara(tradeNo,System.currentTimeMillis()+"");

		while (true) {
			Thread.sleep(1000);

			if(tadeState !=null && tadeState.get(no)!=null){
				//结束循环
				break;
			}else{
				//超时
				Thread.sleep(timeOut);
				isTimeOut = true;
				break;
			}
		}
		if(isTimeOut){
			text = "已超时！！！";
			ret = Ret.fail().set("msg", text);
		}else {
			text = tadeState.get(no).toString();
			ret = Ret.ok().set("msg", text);
		}
		renderJson(ret);
	}

	public void changestate() throws InterruptedException {
		//清空 map;
		tadeState.clear();
		String no = getPara(tradeNo,System.currentTimeMillis()+"");
		Thread.sleep(1000);
		tadeState.put(no, "交易成功！！");
		printLog();
		renderJson("");
	}

	private void printLog(){
		for (Map.Entry en  : tadeState.entrySet()){
			LogKit.debug(en.getKey()+"======"+en.getKey().toString());
			System.out.println(en.getKey()+"======"+en.getKey().toString());
		}
	}

	public void code(){

		//render(new PhotoQrCode("xxx", 300, 300,"http://www.gtdblog.com/wp/wp-content/uploads/2017/09/meyou4-1.png",0xff9966));
		String path = getRequest().getSession().getServletContext().getRealPath("/")+"/img/code_logo.png";
		LogKit.debug(path);
		render(new PhotoQrCode("xxx", 500, 500,path,
				0x33CC33,
				0x000CC));
	}
}



